Skip to content

fix(maths): include index n in the eulers_totient sieve - #15767

Open
divya0795 wants to merge 1 commit into
TheAlgorithms:masterfrom
divya0795:fix-eulers-totient-last-index
Open

divya0795 wants to merge 1 commit into
TheAlgorithms:masterfrom
divya0795:fix-eulers-totient-last-index

Conversation

@divya0795

Copy link
Copy Markdown

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Problem

maths/eulers_totient.py totient(n) is a linear sieve that returns a list of length n + 1 with totients[i] = φ(i). The sieve stops one index too early:

for j in range(len(primes)):
    if i * primes[j] >= n:
        break

Because of >=, index n is never marked as composite or updated, so totients[n] keeps its initial value n - 1 (the formula for a prime). For every composite n, the last entry of the returned list is wrong. The doctest prints only indices 1..n-1, so CI never sees it.

Reproduced on free-threaded CPython 3.15.2 (the version in .python-version) at 30507bb:

>>> totient(4)[4], totient(6)[6], totient(10)[10], totient(100)[100]
(3, 5, 9, 99)        # φ = 2, 2, 4, 40

For n = 2..300, totient(n)[n] is wrong for 237 of 299 values: every composite n.

Fix

-            if i * primes[j] >= n:
+            if i * primes[j] > n:

i * primes[j] <= n is always a valid index into the n + 1-long lists, so the bound can include n.

This is a code-only change. The existing doctest prints indices 1..9 for n = 10, and those are the same before and after.

Behaviour change, checked against master

For every n in 0..400, I compared the full returned lists on master and on this branch:

  • indices 0..n-1: identical (0 differences)
  • index n: changed for 321 values of n, all of them composite n that were wrong on master
  • on this branch, every index i >= 2 equals a brute-force φ(i) = #{k ≤ i : gcd(k, i) = 1}

Index 1 is still 0, as the current doctest asserts (φ(1) is 1 by definition). I left that alone because changing it would change the doctest output.

Validation (free-threaded CPython 3.15.2, macOS arm64)

  • A local regression test (totient(10)[10] == 4, totient(n)[n] == φ(n) for n = 2..300, and totient(200)[2:] against brute force) fails on master and passes with this change. I kept it out of this PR because AGENTS.md asks not to change code and its doctests in the same PR. I can open the doctests as a follow-up PR if that helps.
  • uv run --with=pytest-run-parallel pytest --iterations=8 --parallel-threads=auto --ignore-gil-enabled maths/eulers_totient.py: all pass.
  • The full CI pytest command from build.yml gives the same result as on master (4139 passed, plus the same 2 environment-dependent failures as master on macOS: the gaussian_distribution RNG doctest and the network-dependent instagram_crawler doctest).
  • uvx pre-commit run --files maths/eulers_totient.py: all hooks pass. uvx ruff check .: all checks passed.

Checklist

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues, then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

🤖 Generated with Claude Code

The sieve broke on i * primes[j] >= n, so index n was never updated and totient(n)[n] stayed n - 1 for every composite n (totient(10)[10] == 9, phi(10) == 4). Use > n so the last entry is sieved too.
@algorithms-keeper algorithms-keeper Bot added awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files labels Nov 17, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants